//  解决问题： 可以让Promise.then 可以进行链式调用
//  目标： then 方法要链式调用那么就需要返回一个 Promise 对象
//         then 方法里面 return 一个返回值作为下一个 then 方法的参数，如果是 return 一个 Promise 对象，那么就需要判断它的状态



const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECT = 'reject'

class MyPromise4 {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }

    status = PENDING;

    value = null;

    reason = null;


    onFulfilledCallbacks = [];

    onRejectedCallbacks = [];

    resolve = (value) => {
        if (this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;

            while (this.onFulfilledCallbacks.length) {
                this.onFulfilledCallbacks.shift()(value)
            }
        }
    }

    reject = (reason) => {
        if (this.status === PENDING) {
            this.status = REJECT;
            this.reason = reason;

            while (this.onRejectedCallbacks.length) {
                this.onRejectedCallbacks.shift()(reason)
            }
        }
    }


    then(onFulfilled, onRejected) {
        // 为了链式调用这里直接创建一个 MyPromise，并在后面 return 出去
        const promise2 = new MyPromise4((resolve, reject) => {
            if (this.status === FULFILLED) {
                // 状态为FULFILLED 立刻执行回调
                const x = onFulfilled(this.value);
                // 传入 resolvePromise 集中处理
                resolvePromise(x, resolve, reject)
            } else if (this.status === REJECT) {
                // 不需要进行处理,因为失败就不会链式调用了
                onRejected(this.reason);
            } else if (this.status === PENDING) {

                this.onFulfilledCallbacks.push(onFulfilled);
                this.onRejectedCallbacks.push(onRejected);

            }
        })
        return promise2;
    }



}

function resolvePromise(x, resolve, reject) {
    // 判断x是不是 MyPromise 实例对象
    if (x instanceof MyPromise4) {
        // 执行 x，调用 then 方法，目的是将其状态变为 fulfilled 或者 rejected
        // x.then(value => resolve(value), reason => reject(reason))
        // 简化之后
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x)
    }
}

const promise = new MyPromise4((resolve, reject) => {
    // 目前这里只处理同步的问题
    resolve('success')
})

function other() {
    return new MyPromise4((resolve, reject) => {  // 返回的x是promise执行他的resolve,reject
        resolve('other')
    })
}

promise.then(value => {
    console.log(1)
    console.log('resolve', value)
    return other() // 返回Promise，经过resolvePromise返回MyPromise4.then((resolve, reject) => {resolve('other')})
}).then(value => {
    console.log(2)
    console.log('resolve', value)
})


